# -*-coding:Utf-8 -* 
""" UI Image class
"""
from bge import texture, logic
import bgl

class Image(object):

	_declared_Image = {}

	def __new__(cls, path, linear = True):
		if path not in cls._declared_Image:
			cls._declared_Image[path] = object.__new__(cls)
			cls._declared_Image[path].loaded = False
			id_buf = bgl.Buffer(bgl.GL_INT, 1)
			bgl.glGenTextures(1, id_buf)
			cls._declared_Image[path].gl_id = id_buf.to_list()[0]
			cls._declared_Image[path]._source = None
		return cls._declared_Image[path]

	def __del__(self):
		if self.loaded:
			self.unload()
		
	def __init__(self, path, linear = True):
		if not self.loaded:
			image = texture.ImageFFmpeg(logic.expandPath(path))
			image.scale = False
			image.refresh()
			if image.image != None:
				self._source = image
				print('id:',self.gl_id)
				bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.gl_id)
				texfilter = bgl.GL_NEAREST
				if linear:
					texfilter = bgl.GL_LINEAR
				bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER, texfilter)
				bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MIN_FILTER, texfilter)
				bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
				bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_MODULATE)
				bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA, image.size[0], image.size[1], 0, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, image.image)
				bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
				self.loaded = True
	
	def unload(self):
		if self.gl_id:
			id_buf = bgl.Buffer(bgl.GL_INT, 1, (self.gl_id,))
			bgl.glDeleteTextures(1, id_buf)
		if self.loaded:
			self._source = None
			self.loaded = False
	
	@classmethod
	def freeAllTex(cls):
		keys = tuple(cls._declared_Image.keys())
		for tex in keys:
			cls._declared_Image[tex].unload()
		
	@property
	def id(self):
		return self.gl_id
	@property
	def width(self):
		if self._source:
			return self._source.size[0]
		else:
			return 0
	@property
	def height(self):
		if self._source:
			return self._source.size[1]
		else:
			return 0
